package com.feihe.util;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
    
    public static String getRealIp(HttpServletRequest request) {
        String ip = null;
        
        // 先从HTTP_CLIENT_IP获取
        String clientIp = request.getHeader("HTTP_CLIENT_IP");
        if (clientIp != null && !clientIp.isEmpty()) {
            ip = clientIp;
        }
        
        // 从X-Forwarded-For获取
        String forwardedFor = request.getHeader("X-Forwarded-For");
        if (forwardedFor != null && !forwardedFor.isEmpty()) {
            String[] ips = forwardedFor.split(", ");
            if (ip != null) {
                // 将ip插入到数组开头
                String[] newIps = new String[ips.length + 1];
                newIps[0] = ip;
                System.arraycopy(ips, 0, newIps, 1, ips.length);
                ips = newIps;
                ip = null;
            }
            
            for (String ipAddr : ips) {
                if (!ipAddr.matches("^(10|172\\.16|192\\.168)\\..*")) {
                    ip = ipAddr;
                    break;
                }
            }
        }
        
        String finalIp = ip != null ? ip : request.getRemoteAddr();
        
        if (finalIp == null || finalIp.isEmpty()) {
            return "";
        }
        
        String[] ipParts = finalIp.split("\\.");
        if (ipParts.length >= 2 && 
            (("42".equals(ipParts[0]) && "120".equals(ipParts[1])) || 
             ("42".equals(ipParts[0]) && "121".equals(ipParts[1])))) {
            
            String forwarded = request.getHeader("X-Forwarded-For");
            if (forwarded != null && !forwarded.isEmpty()) {
                String[] forwardedArray = forwarded.split(",");
                return forwardedArray[0].trim();
            }
        }
        
        return finalIp;
    }
} 